package com.bestvike.stone.spring.quartz.core;

import org.quartz.Job;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.util.Assert;

/**
 * Created by 许崇雷 on 2018-08-27.
 */
public final class DelegatingJobFactory implements JobFactory {
    private final JobFactory delegate;

    /**
     * Create new instance of DelegatingJobFactory
     *
     * @param delegate JobFactory instance
     */
    public DelegatingJobFactory(JobFactory delegate) {
        Assert.notNull(delegate, "delegate can not be null");
        this.delegate = delegate;
    }

    /**
     * Called by the scheduler at the time of the trigger firing, in order to
     * produce a <code>Job</code> instance on which to call execute.
     *
     * <p>
     * It should be extremely rare for this method to throw an exception -
     * basically only the the case where there is no way at all to instantiate
     * and prepare the Job for execution.  When the exception is thrown, the
     * Scheduler will move all triggers associated with the Job into the
     * <code>Trigger.STATE_ERROR</code> state, which will require human
     * intervention (e.g. an application restart after fixing whatever
     * configuration problem led to the issue wih instantiating the Job.
     * </p>
     *
     * @param bundle    The TriggerFiredBundle from which the <code>JobDetail</code>
     *                  and other info relating to the trigger firing can be obtained.
     * @param scheduler a handle to the scheduler that is about to execute the job.
     * @return the newly instantiated Job
     * @throws SchedulerException if there is a problem instantiating the Job.
     */
    @Override
    public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
        return new DelegatingJob(this.delegate.newJob(bundle, scheduler));
    }
}
